<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="a" :src="a" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-show="percentshow" type="circle" :percentage="percent" class="progress" />
    </el-upload>
  </div>
</template>

<script>
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDCB5pNCmhKhHsFNgLFvLVWIn3LmzxsmUy', // 身份识别ID
  SecretKey: 'Qlt40l9JCMJ0TghZCY5QXS5PWO0qUt1r' // 身份秘钥
})
export default {
  model: { // 使用model， 这儿2个属性，prop属性说，我要将msg作为该组件被使用时（此处为aa组件被父组件调用）v-model能取到的值，event说，我emit ‘cc’ 的时候，参数的值就是父组件v-model收到的值。
    prop: 'a',
    event: 'chuangeifu'
  },
  // props: {

  // },
  props: {
    a: {
      type: String,
      required: true
    }
  },

  data() {
    return {
      // aa: '',
      percent: 0, // 显示进度条的,
      percentshow: false
    }
  },
  methods: {
    upload(res) {
      if (res.file) {
        this.percentshow = true
        // 执行上传操作
        cos.putObject({
          Bucket: 'mangoxin1-1305723381', /* 存储桶 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => { // 上传进度
            this.percent = progressData.percent * 100
            console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            console.log(this.imageUrl)

            const imageUrl = `https:${data.Location}`
            this.$emit('chuangeifu', imageUrl)
            // console.log(this.imageUrl)
            this.percentshow = false
          }
        })
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png' || 'image/jpg' || 'image/svg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
